import {Overlay} from 'ol'
import {toLonLat, transform} from 'ol/proj'
import Measure from './measure'
import {toStringHDMS} from "ol/coordinate";
import {Style, Fill, Stroke, Text} from 'ol/style'
import LayerVector from 'ol/layer/Vector'
import VectorSource from "ol/source/Vector";

export default {
    data() {
        return {
            markerArr: [], // 位置搜索数组
            isWeatherView: false,
            isLengthMeasuring: false,
            isAreaMeasuring: false,
            isTrendLengthMeasuring: false,
            weatherData: '',
            weatherLoading: false,
            drawing: false, // 是否作画中
            PI: 3.14159265358979324,
            x_PI: (3.14159265358979324 * 3000.0) / 180.0,
            a: 6378245.0,
            ee: 0.00669342162296594323,
            pointArr: [], // 添加圆点图层的经纬度集合
            addPointLayer: [], // 添加圆点图层的图层集合
            selectPointId: null, // 选中点的id
            isMousePosition: false, // 控制鼠标移动展示经纬度控件
            highlightStyle: new Style({
                stroke: new Stroke({
                    color: '#f00',
                    width: 1
                }),
                fill: new Fill({
                    color: 'rgba(255, 0, 0, 0.1)'
                }),
                text: new Text({
                    font: '12px Calibri, sans-serif',
                    fill: new Fill({
                        color: '#000'
                    }),
                    stroke: new Stroke({
                        color: '#f00',
                        width: 3
                    })
                })
            }),
            highlight: null,
            featureOverlay: null,

        }
    },
    methods: {

        // 静态测距
        lengthMeasure() {
            // 如果点击了测距并没有在地图上测量而是直接点击了测面，会发现测距和测面同时进行，这个函数就是用来解决这个问题
            Measure.measure(this.map, 'LineString', () => {
                this.isLengthMeasuring = false
            })
        },
        // 测面积
        areaMeasure() {
            Measure.measure(this.map, 'Polygon', () => {
                this.isAreaMeasuring = false
            })
        },
        clearAll() {
            Measure.deleteAllLayers(this.map)
        },
        // 1.2.2版本modify
        weatherViewAdd(midValue) {
            const weatherIcon = this.$refs['weather-move-icon']
            weatherIcon.onclick = () => {
                if (this.isWeatherView) {
                    this.weatherData = []
                    this.weatherLoading = true
                    const coordinate = midValue
                    const dealCoordinates = this.transform3857to4326(coordinate[0], coordinate[1])
                    this.getSelectedWeather(dealCoordinates[0], dealCoordinates[1])
                    const markerTool = new Overlay({
                        element: this.$refs['weather-icon'],
                        positioning: 'center-center',
                        offset: [0, 0],
                        stopEvent: false
                    })
                    this.map.addOverlay(markerTool)
                    markerTool.setPosition(coordinate)
                }
            }
            weatherIcon.onmousedown = () => {
                this.mousedownUpIcon = 'touchDown'
            }
            weatherIcon.onmouseup = () => {
                this.mousedownUpIcon = 'normalMove'
            }
        },
        transform3857to4326(lon, lat) {
            return transform([lon, lat], 'EPSG:3857', 'EPSG:4326')
        },
        clearSelectLauer(val) {
            // 在其他操作的时候清除select图层，再其他操作结束继续可选select
            if (val) {
                if (this.toggleSelectClick) this.map.removeInteraction(this.toggleSelectClick)
                if (this.dragSelect) this.map.removeInteraction(this.dragSelect)
                this.hasSelectedArr = []
                this.leftExtend = false
                this.rightExtend = false
                this.panelExtend = false
                if (this.choosing) {
                    this.choosing = false
                    this.map.removeControl(this.pointOverlay[this.stepArr[this.step]].mousePositionControl)
                    this.map.un('singleclick', this.pointOverlay[this.stepArr[this.step]].singleclickControl)
                    this.pointOverlay[this.stepArr[this.step]].show = false
                }
            } else {
                this.toggleSelect()
                this.dragBoxSelect()
            }
        },
        /** ************************** 添加的工具栏 **********************************/
        move() {
            let _this = this;
            let swipe = document.getElementById("swipeContainer");
            let obj = {};
            swipe.onmousedown = function (event) {
                let e = event || window.event;
                // 鼠标点击元素那一刻相对于元素左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
                obj.diffX = e.clientX - this.offsetLeft;
                document.onmousemove = function (event) {
                    let e = event || window.event;
                    let moveX = e.clientX - obj.diffX;
                    if (moveX < 0) {
                        moveX = 0;
                    } else if (moveX > 870) {
                        moveX = 870;
                    }
                    // console.log(moveX);
                    _this.value = swipe.offsetWidth;
                    swipe.style.left = moveX + "px";
                    _this.LayerSwipes();
                    //重新渲染图层
                    _this.map.render();
                };
                document.onmouseup = function () {
                    this.onmousemove = null;
                    this.onmouseup = null;
                };
            };
        },
        LayerSwipes() {
            let _this = this;
            this.layer.on("prerender", (event) => {
                let swipe = document.getElementById("swipeContainer");
                let ctx = event.context;
                //计算图层在canvas画布上需要显示的范围
                let mapSize = _this.map.getSize();
                let height = event.context.canvas.height;
                let width = event.context.canvas.width;
                let swipeWidth = swipe.offsetLeft * width / mapSize[0];
                // console.log(swipeWidth);
                let tl = [swipeWidth, 0];
                let tr = [width, 0];
                let bl = [swipeWidth, height];
                let br = [width, height];

                ctx.save();
                //绘制裁剪路径
                ctx.beginPath();
                ctx.moveTo(tl[0], tl[1]);
                ctx.lineTo(bl[0], bl[1]);
                ctx.lineTo(br[0], br[1]);
                ctx.lineTo(tr[0], tr[1]);
                ctx.closePath();
                //裁剪，裁剪路径以外的部分不会绘制在canvas上下文中
                ctx.clip();
            });

            this.layer.on("postrender", (event) => {
                // 在Bing地图渲染之后触发
                let ctx = event.context;
                ctx.restore();
            });
        },
        //弹窗显示
        showPop() {
            //    弹窗
            this.overlay = new Overlay({
                element: this.$refs.popup, // 弹窗标签，在html里
                autoPan: true, // 如果弹窗在底图边缘时，底图会移动
                autoPanAnimation: { // 底图移动动画
                    duration: 250
                }
            })
            this.map.addOverlay(this.overlay)
            this.map.on("singleclick", evt => {
                const coordinate = evt.coordinate // 获取坐标
                const hdms = toStringHDMS(toLonLat(coordinate))//转换坐标格式
                console.log(coordinate)
                this.currentCoordinate = hdms
                this.overlay.setPosition(coordinate)
            })
        },
        //矢量图高亮
        displayFeatureInfo() {
            if (!this.featureOverlay) {
                this.featureOverlay = new LayerVector({
                    source: new VectorSource(),
                    map: this.map,
                    style: feature => {
                        this.highlightStyle.getText().setText(feature.getName('name'))
                        return this.highlightStyle
                    }
                })
            }
            let feature = this.map.forEachFeatureAtPixel(pixel, feature => feature)
            let info = this.$refs.info
            if (feature) {
                info.innerHTML = feature.getId() + ': ' + feature.get('name')
            } else {
                info.innerHTML = "&nbsp;"
            }
            if (feature !== this.highlight) {
                if (this.highlight) {
                    this.featureOverlay.getSource().removeFeature(this.highlight)
                }
                if (feature) {
                    this.featureOverlay.getSource().addFeature(feature)
                }
                this.highlight = feature
            }
        },
        vectorHigh() {

        },


    }
}
